package top.lixunda.books3.controller;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import top.lixunda.books3.entity.BookWithBLOBs;
import top.lixunda.books3.entity.Slide;
import top.lixunda.books3.entity.User;
import top.lixunda.books3.model.SimpleBook;
import top.lixunda.books3.service.*;
import top.lixunda.books3.util.Log;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RequestMapping("/page")
@Controller
public class PageController {

    private final SlideService slideService;

    private final BookService bookService;

    private final UserService userService;

    private final IndexRecommendService recommendBooksService;

    private final RecommendService userBookTagService;

    @Autowired
    public PageController(SlideService slideService, BookService bookService, UserService userService,
                          IndexRecommendService recommendBooksService, RecommendService userBookTagService) {
        this.slideService = slideService;
        this.bookService = bookService;
        this.userService = userService;
        this.recommendBooksService = recommendBooksService;
        this.userBookTagService = userBookTagService;
    }

    @RequestMapping(value = "/index")
	public ModelAndView pageIndex(@CookieValue(value = "save", required = false, defaultValue = "false") String save,
                                  @CookieValue(value = "loginKey", required = false, defaultValue = "") String key,
                                  @SessionAttribute(value = "user", required = false) User user){
		ModelAndView view = new ModelAndView();
		//1. 设置转向页面index.jsp
		view.setViewName("index");
		//2 设置自动登录
        if(user == null){
            Log.d("已经登录了  save = "+save+"   key = "+key);
            if( "true".equals(save) && key.length() != 0){
                Log.d("-------》 设置了自动登录");
                if(userService.keyLogin(key)){
                    Log.d("------------->自动登录成功");
                }else{
                    Log.d("------------->自动登录失败");
                }
            }else{
                Log.d("-------》 没有设置自动登录");
            }
        }
		//3. 获取热搜标签 (暂时没有统计，直接给出结果)
        List<String> hots = new ArrayList<>();
        hots.add("Linux");
        hots.add("Android");
        hots.add("经济学");
        hots.add("SSM");
        view.addObject("hots", hots);
        Log.d("------------> hots : "+new Gson().toJson(hots));
		//4. 获取轮播图信息并保存
        List<Slide> slideList = slideService.selectUsingSlides();
        view.addObject("slideList", slideList);
        Log.d("------------> slideList : "+new Gson().toJson(slideList));
        //5. 获取推荐图书列表 包括推荐列表，按类别推荐列表和新书列表
        Map<String, List<SimpleBook>> map = recommendBooksService.selectAllSimpleBooks();
        view.addObject("recommend", map);
        Log.d("------------> recommendBooks map : "+new Gson().toJson(map));
		return view;
	}

	@RequestMapping(value = "/book/id/{id}")
	public ModelAndView pageBookId(@PathVariable("id") String id, @SessionAttribute(value = "user", required = false) User user){
	    ModelAndView modelAndView = new ModelAndView();
	    //1. 设置跳转页面
        modelAndView.setViewName("book");
        //2. 获取热搜标签 (暂时没有统计，直接给出结果)
        List<String> hots = new ArrayList<>();
        hots.add("Linux");
        hots.add("Android");
        hots.add("经济学");
        hots.add("SSM");
        modelAndView.addObject("hots", hots);
        Log.d("------------> hots : "+new Gson().toJson(hots));
        //3. 转换类型
        Log.d("-----> 初始的 BookId ： "+id);
        long bookId;
        try{
            bookId = Long.parseLong(id);
        }catch (Exception e){
            return modelAndView;
        }
        //4. 获取并保存书籍信息
        BookWithBLOBs book = bookService.selectBookWithBLOBsById(bookId);
        //4.1 替换换行符 JSTL无法处理
        book.setCatalog(book.getCatalog().replace("\n", "!@#"));
        modelAndView.addObject("book", book);
        Log.d("------------> 书籍信息 : "+new Gson().toJson(book));
        //5. 保存用户行为
        userBookTagService.insertBookTags(user, book);
        bookService.clickBookOnce(book);
        //6. 查询订单信息

	    return modelAndView;
    }

    @RequestMapping(value = "/user")
    public ModelAndView pageUser(HttpSession session){
        ModelAndView modelAndView = new ModelAndView();
        //1. 设置转向页面
        if(session.getAttribute("user") == null){
            //未登录，重定向到首页
            modelAndView.setViewName("redirect:./index.do");
            return modelAndView;
        }
        modelAndView.setViewName("user");
        return modelAndView;
    }

    @RequestMapping(value = "/userMain/{page}")
    public ModelAndView pageUserMain(@PathVariable(value = "page") String page){
	    ModelAndView modelAndView = new ModelAndView();
        //1. 设置转向页面
        modelAndView.setViewName("userMain"+page);
        return modelAndView;
    }

    @RequestMapping(value = "/userMain1/{page}")
    public ModelAndView pageUserMain1(@PathVariable(value = "page") String page){
        ModelAndView modelAndView = new ModelAndView();
        //1. 设置跳转页面
        modelAndView.setViewName("userMain1_"+page);
        return modelAndView;
    }


	@RequestMapping(value= "/{pageName}",method=RequestMethod.GET)
	public String showPage(@PathVariable("pageName")String pageName) {
		return pageName;
	}
}